//
//  NSObject+AssetsImageManager.m
//  YuanXinCamera
//
//  Created by wangxue on 16/10/10.
//  Copyright © 2016年 晏德智. All rights reserved.
//

#import "NSObject+AssetsImageManager.h"

#define iOS8Later ([UIDevice currentDevice].systemVersion.floatValue >= 8.0f)
@implementation NSObject (AssetsImageManager)

// 获取原图
- (void)getOriginalPhotoWithAsset:(NSURL*)assetURL completion:(void (^)(UIImage *photo,NSDictionary *info))completion {
    id asset = [self getAssetFromAssetURL:assetURL];
    if ([asset isKindOfClass:[PHAsset class]]) {
        PHImageRequestOptions *option = [[PHImageRequestOptions alloc]init];
        option.networkAccessAllowed = YES;
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            BOOL downloadFinined = (![[info objectForKey:PHImageCancelledKey] boolValue] && ![info objectForKey:PHImageErrorKey]);
            if (downloadFinined && result) {
                result = [self fixOrientation:result];
                if (completion) completion(result,info);
            }
        }];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    } else if ([asset isKindOfClass:[ALAsset class]]) {
        ALAsset *alAsset = (ALAsset *)asset;
        ALAssetRepresentation *assetRep = [alAsset defaultRepresentation];
#pragma clang diagnostic pop
        
        dispatch_async(dispatch_get_global_queue(0,0), ^{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
            CGImageRef originalImageRef = [assetRep fullResolutionImage];
#pragma clang diagnostic pop
            UIImage *originalImage = [UIImage imageWithCGImage:originalImageRef scale:1.0 orientation:UIImageOrientationUp];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) completion(originalImage,nil);
            });
        });
    }
}

- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

- (id)getAssetFromAssetURL:(NSURL *)assetURL {
    
   if ([assetURL isKindOfClass:[NSString class]]) {
       
        assetURL = [NSURL URLWithString:assetURL];
    }
    id asset;
    
    if (iOS8Later) {
        
        
        PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[assetURL] options:nil];
        if(fetchResult.count == 0){
            
            fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetURL.absoluteString] options:nil];
        }

         asset = fetchResult.firstObject;
        
       }else{
        
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        [library assetForURL:assetURL resultBlock:^(ALAsset *asset) {
            
           asset = asset;
            
        } failureBlock:^(NSError *error) {
            NSLog(@"%@",error);
        }];
    }
     return asset;
}



/*- (NSString *)getCoverImageData:(UIImage *)image {
    
    NSData *ImageData;
    //判断图片是不是png格式的文件
    if (UIImagePNGRepresentation(image)) {
        
        ImageData = UIImagePNGRepresentation(image);
        
        
    }else {
        //返回为JPEG图像。
        ImageData = UIImageJPEGRepresentation(image, 0.1);
        
    }
    
    NSString *base64Encoded = [ImageData base64EncodedStringWithOptions:0];
    
    return base64Encoded;
    
}

- (NSString *)getSmallImageData:(UIImage *)image AndWidth:(CGFloat)width {
    
    
    //缩略图
    CGFloat height = (image.size.height/image.size.width)*width;
    CGSize smallImageSize = CGSizeMake(width, height);
    UIImage *smallImage = [image scaleToSize:smallImageSize];
    NSString *smallbase64Encoded = [self getCoverImageData:smallImage];
    
    return smallbase64Encoded;
}*/


@end
